package com.wlbx.agent.ui.activity;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.logger.Logger;
import com.wlbx.agent.R;
import com.wlbx.agent.base.BaseActivity;
import com.wlbx.agent.net.RequestManager;
import com.wlbx.agent.net.RetrofitCallBack;
import com.wlbx.agent.net.RetrofitRequestInterface;
import com.wlbx.agent.util.SPUtil;
import com.wlbx.agent.view.rectangleboxedittext.VerificationCodeView;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class ValidCodeActivity extends BaseActivity {
    private static final String TAG = "ValidCodeActivity";

    @BindView(R.id.tv_layout_top_back_title)
    TextView mTitleTV;
    @BindView(R.id.iv_layout_top_back)
    ImageView mBackIV;
    @BindView(R.id.et_rectangle)
    VerificationCodeView et_rectangle;
    @BindView(R.id.tv_pop_phone_getvalidcode)
    TextView mGetValidCodeTV;
    @BindView(R.id.tv_time)
    TextView tvTime;
    private String phone;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_validcode;
    }

    @Override
    public void initData() {
        phone = getIntent().getStringExtra("phone");
        mTitleTV.setText("输入验证码");
        mGetValidCodeTV.setEnabled(false);
        et_rectangle.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                if(et_rectangle.getInputContent().length()==4){
                    timer.cancel();
                    toSaveNewPhone();
                }
            }
        });
        timer.start();
    }

    @Override
    public void initEvent() {}

    @OnClick({R.id.iv_layout_top_back,R.id.tv_pop_phone_getvalidcode})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_layout_top_back:
                finish();
                break;
            case R.id.tv_pop_phone_getvalidcode:
                getNewValidCode();
                break;
            default:
                break;
        }
    }

    public void getNewValidCode(){
        RequestManager
        .mRetrofitManager
        .createRequest(RetrofitRequestInterface.class)
        .getNewPhoneValidCode(phone)
        .enqueue(new RetrofitCallBack() {
            @Override
            public void onSuccess(String response) {
                Logger.i(TAG, response);
                JSONObject jsonObject = JSON.parseObject(response);
                String rCode = jsonObject.getString("code");
                String rMsg  = jsonObject.getString("msg");
                if("1000".equals(rCode)) {
                    Toast.makeText(mContext,"获取验证码成功",Toast.LENGTH_SHORT).show();
                    timer.start();
                }else{
                    Toast.makeText(mContext,rMsg,Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onError(Throwable t) {
                Logger.i(TAG, t.getMessage());
                Toast.makeText(mContext,"获取验证码失败"+t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    //保存新手机号码
    public void toSaveNewPhone(){
        final Map<String, String> map = new HashMap<>();
        map.put("mobile", phone);
        map.put("validateCode", et_rectangle.getInputContent());
        Logger.i(TAG, JSON.toJSONString(map));
        RequestManager
        .mRetrofitManager
        .createRequest(RetrofitRequestInterface.class)
        .toSaveNewPhone(JSON.toJSONString(map))
        .enqueue(new RetrofitCallBack() {
            @Override
            public void onSuccess(String response) {
                Logger.i(TAG, response);
                JSONObject jsonObject = JSON.parseObject(response);
                String rCode = jsonObject.getString("code");
                String rMsg  = jsonObject.getString("msg");
                if("1000".equals(rCode)) {
                    returnToPre();
                }else {
                    Toast.makeText(mActivity, rMsg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable t) {
                Logger.i(TAG, t.getMessage());
                Toast.makeText(mContext,"手机号保存失败"+t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    //返回到前一个页面
    public void returnToPre(){
        timer.cancel();
        Intent intent = new Intent();
        this.setResult(1,intent);
        this.finish();
    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvTime.setText("("+millisUntilFinished/1000 + "s)");
        }

        @Override
        public void onFinish() {
            mGetValidCodeTV.setEnabled(true);
            tvTime.setText("");
        }
    };


}